﻿package net.jmp0.toast.entities.interfaces.wobblingBehavior
{
	import net.jmp0.toast.entities.bases.GameElement;
	import net.jmp0.toast.entities.interfaces.wobblingBehavior.WobblingBehavior;
	import punk.Acrobat;
	
	/**
	 * Calculates the relative Drawingtranslation used for a "wobbling" motion
	 * @author Thodd
	 */
	public class DoWobble extends Acrobat implements WobblingBehavior
	{
		private var container:GameElement;
		
		private var isWobbling:Boolean = false;
		private var initiator:GameElement;
		
		private var maxTravelDistance:int = 4;
		private var distanceTraveled:int = 0;
		private var initiatorXSpeed:int = 0;
		private var initiatorYSpeed:int = 0;
		
		private var xstart:int;
		private var ystart:int;
		
		private var drawX:int = 0;
		private var drawY:int = 0;
		
		public function DoWobble(container:GameElement)
		{
			this.container = container;
		}
		
		
		//@implements
		/**
		 * Invokes a wobbling motion in the container element, but only in case it isn't already started.
		 * @param	initiator : The object which initiates the wobbling motion, it's xSpeed and ySpeed are relevant!
		 */
		public function wobble(initiator:GameElement):void {
			
			//Only invoke wobbling if we aren't yet
			if (!isWobbling) {
				this.initiator = initiator;
				initiatorXSpeed = initiator.xSpeed;
				initiatorYSpeed = initiator.ySpeed;
				xstart = container.x;
				ystart = container.y;
				isWobbling = true;
			}
		}
		
		
		override public function update():void {
			//Perform a bouncing motion
			if (isWobbling) {
				//Moving the drawing position of the sprite according to the initiating object's xSpeed and ySpeed
				if(distanceTraveled <= maxTravelDistance){
					drawX += FP.sign(initiatorXSpeed);
					drawY += FP.sign(initiatorYSpeed);
					distanceTraveled += 1;
				}else{
					drawX -= FP.sign(initiatorXSpeed);
					drawY -= FP.sign(initiatorYSpeed);
				}
				
				//if drawX and drawY are back in their starting position -> end the wobbling and accept a new invocation
				if (container.x + drawX == xstart && container.y + drawY == ystart) {
					isWobbling = false;
					distanceTraveled = 0;
					drawX = 0;
					drawY = 0;
				}
				
			}
			
		}
		
		public function getDrawX():int {
			return drawX;
		}
		
		public function getDrawY():int {
			return drawY;
		}
		
		public function destroy():void {
			FP.world.remove(this);
		}
		
	}
	
}